package com.lxw.oa.controller.common;

import com.lxw.oa.controller.BaseController;
import com.lxw.oa.entity.User;
import com.lxw.oa.enums.OnlineStatus;
import com.lxw.oa.service.SysUserOnlineService;
import com.lxw.oa.shiro.session.OnlineSession;
import com.lxw.oa.shiro.session.OnlineSessionDAO;
import com.lxw.oa.util.AjaxResult;
import com.lxw.oa.util.LogAopIn;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Controller
@EnableTransactionManagement
public class LoginController extends BaseController {



    //退出的时候可以用
    @GetMapping("/login")
    public String login(ServletRequest request, HttpServletResponse response, ModelMap modelMap)
    {
        String flag=request.getParameter("flag");
        if(null!=flag&&!"".equals(flag)){
                modelMap.addAttribute("flag",flag);
        }

        return "pages/main/login";
    }

    @PostMapping("/login")
    @ResponseBody
    public AjaxResult ajaxLogin(String username, String password, Boolean rememberMe)
    {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        Subject subject = SecurityUtils.getSubject();
        try
        {
            subject.login(token);
            return success();
        }
        catch (AuthenticationException e)
        {
            String msg = e.getMessage();
            return error(msg);
        }
    }

    //登陆成功时记录
    @LogAopIn(moduleName="系统管理",option="登陆成功")
    @GetMapping("/loginMark")
    @ResponseBody
    public AjaxResult Log_loginMark(HttpServletRequest request)
    {
        System.out.println("===============登陆成功================");
        return success();
    }


    //退出的时候可以用
    @LogAopIn(moduleName="系统管理",option="系统登出")
    @GetMapping("/loginOut")
    public String Log_loginOut(HttpServletRequest request)
    {
/*        Enumeration<String> enumeration = request.getSession().getAttributeNames();
         while (enumeration.hasMoreElements()) {
         String key = enumeration.nextElement().toString();
         request.getSession().removeAttribute(key);
        }*/
            return "redirect:logout";
    }


    @LogAopIn(moduleName="错误",option="跳转错误提示页面")
    @GetMapping("/unauth")
    public String Log_unauth()
    {
        return "error/unauth";
    }

}
